import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:path_provider/path_provider.dart';

class CgqUtils {
  /// toast
  static toast(String msg) async {
    await EasyLoading.showToast(msg);
  }

  /// loading
  static loading({String msg}) async {
    await EasyLoading.show(status: msg ?? "loading...");
  }

  /// 关闭loading
  static dismiss() {
    EasyLoading.dismiss();
  }

  /// https://pub.flutter-io.cn/packages/cached_network_image
  /// 缓存图片
  static Widget imageCache(String url, {BoxFit fit, String errorUrl}) {
    return CachedNetworkImage(
        imageUrl: url,
        fit: fit ?? BoxFit.fill,
        placeholder: (context, url) => CupertinoActivityIndicator(
            // color: WcaoTheme.primary,
            ),
        errorWidget: (context, url, error) => errorUrl != null
            ? Image(image: NetworkImage(errorUrl), fit: BoxFit.cover)
            : Image(
                image: NetworkImage(
                    "http://music-live.oss-cn-hangzhou.aliyuncs.com//userBgUrl/202265/app-eLPTZBZmncAp.jpg"),
                fit: BoxFit.cover));
  }

  static String getFileType(String path) {
    print(path);
    List<String> array = path.split(".");
    return array[array.length - 1];
  }

  static String getRandom(int num) {
    String alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    String left = '';
    for (var i = 0; i < num; i++) {
//    right = right + (min + (Random().nextInt(max - min))).toString();
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }

  static saveVideo(String fileUrl, Function onReceiveProgress) async {
    var appDocDir = await getTemporaryDirectory();
    String savePath =
        appDocDir.path + "app-${getRandom(12)}.mp4";
    Dio dio = Dio();
    dio.options.responseType = ResponseType.json;
    dio.options.headers = {
      'Connection': 'keep-alive',
      'sec-ch-ua':
          '" Not A;Brand";v="99", "Chromium";v="90", "Microsoft Edge";v="90"',
      'Accept': '*/*',
      'X-Requested-With': 'XMLHttpRequest',
      'sec-ch-ua-mobile': '?0',
      'User-Agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 Edg/90.0.818.66',
      'Sec-Fetch-Site': 'same-origin',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Dest': 'empty',
      'Referer':
          'https://www.iesdouyin.com/share/video/6561991332561161476/?region=CN&mid=6561671254439365390&u_code=0&titleType=title&did=MS4wLjABAAAA2Cy8LTQsppRk4gci9RcF18kdcuNyaQRtZcZt0BGbylg&iid=MS4wLjABAAAAWHQavP6vURszBFMcxNrThBB0wrNEDWNzLdTKiuW5cI_cOJvn7h0u20Uz8R292pd2&with_sec_did=1&utm_source=copy_link&utm_campaign=client_share&utm_medium=android&app=aweme&scheme_type=1',
      'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
      'Cookie':
          'MONITOR_WEB_ID=4843f090-b627-46db-bbe2-f757b4ea21a0; _tea_utm_cache_1243={%22utm_source%22:%22copy_link%22%2C%22utm_medium%22:%22android%22%2C%22utm_campaign%22:%22client_share%22}'
    };
    await dio.download(fileUrl, savePath, onReceiveProgress: (count, total) {
      print((count / total * 100).toStringAsFixed(0) + "%");
      onReceiveProgress((count / total * 100).toStringAsFixed(0));
    });
    final result = await ImageGallerySaver.saveFile(savePath);
    if (result['isSuccess']) {
      Fluttertoast.showToast(msg: "保存视频成功，保存路径为${result['filePath']}");
    }
  }
}
